#ifndef esda_SQLite_h
#define esda_SQLite_h

/*
 * Copyright (C) Olivier Le Floch
 *
 * See the file LICENSE for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "common.h"
#include "Timestamp.h"

#define SQLite_ERROR(error, query) ERROR("Failed to " << error << " -- " << query << " -- " << sqlite3_errmsg(database));

namespace esda
{
	class SQLite {
	public:
		inline static Timestamp fetchTimestamp(sqlite3 *database, const string& query);
		inline static void runQuery(sqlite3 *database, const string& query);
	};
	
	inline Timestamp SQLite::fetchTimestamp(sqlite3 *database, const string& query) {
		Timestamp t;
		
		sqlite3_stmt *stmt = 0;
		
		if (sqlite3_prepare_v2(database, query.c_str(), -1, &stmt, NULL)) {
			SQLite_ERROR("Create query", query);
		}
		
		if (sqlite3_step(stmt) != SQLITE_ROW) {
			SQLite_ERROR("Run query", query);
		}
		
		t = sqlite3_column_int64(stmt, 0);
		
		if (sqlite3_finalize(stmt)) {
			SQLite_ERROR("Finalize query", query);
		}
		
		return t;
	}
	
	inline void SQLite::runQuery(sqlite3 *database, const string& query) {
		sqlite3_stmt *stmt = 0;
		
		if (sqlite3_prepare_v2(database, query.c_str(), -1, &stmt, NULL)) {
			SQLite_ERROR("Create query", query);
		}
		
		if (sqlite3_step(stmt) != SQLITE_DONE) {
			SQLite_ERROR("Run query", query);
		}
		
		if (sqlite3_finalize(stmt)) {
			SQLite_ERROR("Finalize query", query);
		}
	}
}

#endif
